package com.ls.queue;

/**
 * @program: dataStructure
 * @author: lishun
 * @create: 2021-11-25 09:49
 **/

/**
 * 数组模拟环形队列
 */
public class ArrayCircleQueue {

    /**
     * 队列头
     */
    private int front;
    /**
     * 队列尾部
     */
    private int rear;

    /**
     * 队列能存的最大长度
     */
    private int maxSize;

    /**
     * 数据
     */
    int[] data;

    public static void main(String[] args) {
        ArrayCircleQueue queue = new ArrayCircleQueue(3);
        for (int i = 0; i < 4; i++) {
            queue.add(i);
        }
        for (int i = 0; i < 3; i++) {
            System.out.println(queue.get());
        }
        for (int i = 0; i < 3; i++) {
            queue.add(i);
        }


    }

    public ArrayCircleQueue(int maxSize) {
        this.maxSize = maxSize+1;
        this.data = new int [this.maxSize];
    }

    /**
     * 判断队列是否为空
     */
    public boolean isEmpty(){
        return this.front==this.rear;
    }

    /**
     * 判断队列是否满了
     */

    public boolean isFull(){
        return (this.rear+1)%maxSize==front;
    }

    /**
     * 队列尾添加元素
     */
    public void add(int data){
        if (isFull()){
            throw new RuntimeException("队列满了");
        }
        /**
         * 一直加会越界,所以要取模
         */
        this.data[rear] = data;

        this.rear = (this.rear+1)% maxSize;
    }

    /**
     * 队列头部取得元素
     */
    public int get(){
        if (isEmpty()){
            throw new RuntimeException("队列空了");
        }
        int value = this.data[front];
        this.front = (this.front+1)%maxSize;
        return value;
    }

}
